package org.kl.bf.service.basic;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.entity.basic.CodeTable;
import org.kl.bf.entity.basic.CodeValues;
import org.kl.bf.repository.basic.CodeTableDao;
import org.kl.bf.utils.CRUDUtils;
import org.kl.bf.utils.KLDynamicSpecifications;
import org.kl.bf.utils.KLSearchFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author hqm
 * @CreateTime 2014-3-13 下午9:11:30
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional
public class CodeTableService {

	private CodeTableDao codeTableDao;
	@Autowired
	private CodeValuesService codeValueService;

	public CodeTable getCodeTable(String guid) {
		return codeTableDao.findOne(guid);
	}
	
	public CodeTable getByTableCode(String tableCode) {
		return codeTableDao.findByTableCode(tableCode);
	}

	public void saveCodeTable(CodeTable entity) {
		codeTableDao.save(entity);
	}

	public int deleteCodeTable(String ids) {
		int i = 0;
		for (String id : ids.split(",")) {
			if (StringUtils.isBlank(id)) {
				continue;
			}
			List<CodeValues> cv = codeValueService.getCodeValuesByCodeTableId(id);
			String cids = "";
			if(cv.size()!=0){
				for(int j=0;j<cv.size();j++){
					//System.out.println("Value节点："+cv.get(j).getId());
					cids += (cv.get(j).getId()+",");	
				}
				codeValueService.deleteCodeValues(cids);
			}
			//System.out.println("删除节点Table："+id.trim());
			codeTableDao.delete(id.trim());
			i++;
		}
		return i;
	}

	public List<CodeTable> getAllCodeTable() {
		return codeTableDao.findAll();
	}

	public Page<CodeTable> getUserCodeTable(Map<String, Object> searchParams, int pageNumber, int pageSize,
			String sortType, String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<CodeTable> spec = buildSpecification(searchParams);

		return codeTableDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<CodeTable> buildSpecification(Map<String, Object> searchParams) {
		Map<String, KLSearchFilter> filters = KLSearchFilter.parse(searchParams);
		Specification<CodeTable> spec = KLDynamicSpecifications.byKLSearchFilter(filters.values(), CodeTable.class);
		return spec;
	}

	@Autowired
	public void setCodeTableDao(CodeTableDao codeTableDao) {
		this.codeTableDao = codeTableDao;
	}

	public List<CodeTable> getAll(Map<String, Object> searchParams,String sortType, String orderType) {
		Specification<CodeTable> spec = KLDynamicSpecifications.buildSpecification(searchParams, CodeTable.class);
		return codeTableDao.findAll(spec, CRUDUtils.buildSort(sortType, orderType));
	}

}
